//
//  RHFeedbackVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/11/28.
//

#import "RHFeedbackVC.h"
#import "RHFeedBackTypeCell.h"
#import "RHFbQuestionTypeCell.h"
#import "RHFbSelectDevCell.h"
#import "RHFbContactCell.h"

@interface RHFeedbackVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *titles;

@property (nonatomic ,strong) UIView *footerView;

@property (nonatomic ,strong) NSMutableDictionary *para;

@property (nonatomic ,strong) NSArray *keys;
//要上传的图片
@property (nonatomic ,strong) NSMutableArray *uploadImgs;
//上传之后的返回的图片路径
@property (nonatomic ,strong) NSMutableArray *imgUrls;

@property(nonatomic ,assign) NSInteger uploadIdx;
@end

@implementation RHFeedbackVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"意见反馈".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
}

-(void)setupUI
{
    self.uploadImgs = [NSMutableArray array];
    self.imgUrls = [NSMutableArray array];
    self.titles = @[@"反馈类型".rh_localized,@"问题类型".rh_localized,@"选择设备".rh_localized,@"联系方式".rh_localized];
    self.para = [NSMutableDictionary dictionary];
    self.keys = @[@"type",@"questionType",@[@"deviceId",@"title",@"description",@"images"],@[@"email",@"phoneNumber"]];
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setEstimatedSectionFooterHeight:0];
    [_tableView setSectionFooterHeight:0];
    [_tableView registerClass:[RHFeedBackTypeCell class] forCellReuseIdentifier:@"PEFeedBackCell"];
    [_tableView registerClass:[RHFbQuestionTypeCell class] forCellReuseIdentifier:@"RHFbQuestionTypeCell"];
    [_tableView registerClass:[RHFbSelectDevCell class] forCellReuseIdentifier:@"RHFbSelectDevCell"];
    [_tableView registerClass:[RHFbContactCell class] forCellReuseIdentifier:@"RHFbContactCell"];
    _tableView.tableFooterView = self.footerView;
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, kSafe_bottom, 0));
    }];
    kWeakSelf;
   
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 13.0, *)) {
        _tableView.automaticallyAdjustsScrollIndicatorInsets = NO;
    }
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    

}
-(UIView *)footerView
{
    if(!_footerView){
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 90)];
        _footerView.backgroundColor = CFTabViewBgColor;
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 90)];
        QMUIButton *sureBtn = [[QMUIButton alloc]init];
        [_footerView addSubview:bgView];
        [bgView addSubview:sureBtn];
        
        [sureBtn setTitle:@"提交".rh_localized forState:UIControlStateNormal];
        [sureBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [sureBtn setBackgroundColor:CMainColorGreen];
        sureBtn.layer.cornerRadius = 8;
        sureBtn.layer.masksToBounds = YES;
        kWeakSelf;
        [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf submitAction];
        }];
        
        [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.centerY.mas_offset(0);
            make.height.offset(50);
        }];
    }
    return _footerView;
}


-(void)submitAction
{
    //是否是客诉
    BOOL isComplaint = [self.para[self.keys[0]] isEqual:@(1)];
    
    //问题类型
    if(![self.para objectForKey:self.keys[0]]){
        [QMUITips showError:@"请选择反馈类型".rh_localized];
        return;
    }
    if(![self.para objectForKey:self.keys[2][0]] && isComplaint){
        [QMUITips showError:@"请选择设备".rh_localized];
        return;
    }
    if([[self.para objectForKey:self.keys[2][1]] length]==0){
        [QMUITips showError:@"请输入标题".rh_localized];
        return;
    }
    if([[self.para objectForKey:self.keys[2][2]] length]==0){
        [QMUITips showError:@"请输入描述信息".rh_localized];
        return;
    }
    
    RHFbSelectDevCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    if(cell.photoArr.count == 0 && isComplaint){
        [QMUITips showError:@"请上传图片".rh_localized];
        return;
    }
    
    if([[self.para objectForKey:self.keys[3][0]] length]==0 && isComplaint){
        [QMUITips showError:@"请输入邮箱".rh_localized];
        return;
    }
    
    //客诉有上传图片,产品建议没有
    if(isComplaint){
        [self processPictures:cell.photoArr.copy];
    }else{
        //去掉不要的参数
        [self.para removeObjectForKey:@"deviceId"];//设备id
        [self.para removeObjectForKey:@"images"];//图片
        [self.para removeObjectForKey:@"email"];//邮箱
        [self.para removeObjectForKey:@"phoneNumber"];//手机
        [self commitFormPara];
    }
    
}

//处理图片
-(void)processPictures:(NSArray*)pictures
{
    [QMUITips showLoading:@"压缩图片...".rh_localized inView:self.view];
    NSMutableArray *tempArr = [NSMutableArray array];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (id img in pictures) {
            if([img isKindOfClass:[UIImage class]]){
                UIImage *compressImage = [self compressImageQuality:img toByte:5000];
                [tempArr addObject:compressImage];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTipsInView:self.view];
            self.uploadImgs = tempArr;
            self.uploadIdx = 0;
            //上传图片
            [self uploadImageWith:self.uploadImgs[0]];
        });
    });
}


#pragma mark -------压缩图片质量   maxLength  单位: kb
- (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    
     CGFloat compression = 1;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length / 1024 > maxLength && compression > 0) {
         compression -= 0.05;
         // When compression less than a value, this code dose not work
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"====>压缩了一次后: %ld k",(long)(data.length / 1024));
     }
     UIImage *resultImage = [UIImage imageWithData:data];
     return resultImage;
}


#pragma mark -------- 图片上传 ----------------
-(void)uploadImageWith:(UIImage *)image
{
    kWeakSelf;
    [QMUITips showLoading:@"上传图片...".rh_localized inView:self.view];
    [BaseModel startUploadWithCompletionAPIKey:H_uploadImage rgument:@{@"file":@"feedback"} image:image imageName:nil requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            
            
            NSString *newFileName = request.responseObject[@"newFileName"];
            NSString *imgName = [[newFileName componentsSeparatedByString:@"_"]lastObject];
            NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
            [mtbDic setObject:imgName forKey:@"name"];
            [mtbDic setObject:request.responseObject[@"fileName"] forKey:@"url"];
            [mtbDic setObject:request.responseObject[@"url"] forKey:@"fileUrl"];
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            NSString *timeStr = [formatter stringFromDate:[NSDate date]];
            [mtbDic setObject:timeStr forKey:@"uid"];
            [weakSelf.imgUrls addObject:mtbDic];
    
            
            weakSelf.uploadIdx++;
            //图片上传完了,上传文件
            if(weakSelf.uploadIdx == weakSelf.uploadImgs.count){
                //字典数组转成字符提交
                NSString *imagesStr = [weakSelf.imgUrls yy_modelToJSONString];
                imagesStr = [imagesStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                imagesStr = [imagesStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
                while ([imagesStr containsString:@" "]) {
                    imagesStr = [imagesStr stringByReplacingOccurrencesOfString:@" " withString:@""];
                }
                [weakSelf.para setObject:imagesStr forKey:@"images"];
                //提交参数
                [weakSelf commitFormPara];
            }else{
                //继续上传下一张图片
                UIImage *image = weakSelf.uploadImgs[weakSelf.uploadIdx];
                [weakSelf uploadImageWith:image];
                
            }
           
          }
        
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           
        }];
}

//提交表单
-(void)commitFormPara
{
    
    [QMUITips showLoadingInView:self.view];
    
    [BaseModel startWithCompletionAPIKey:H_feedback argument:self.para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"提交成功".rh_localized];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if([self.para[self.keys[0]] isEqual:@(2) ]){
        return self.titles.count - 1;
    }
   return self.titles.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 55;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

   
    UIView *header = kView;
    header.backgroundColor = CFTabViewBgColor;
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, kUI_WINDOW_W-30, 40)];
    [header addSubview:bgView];
    bgView.backgroundColor = UIColor.whiteColor;
    [bgView setTopBorder];
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    
    
    
    QMUILabel *feedbackTitleLab = [[QMUILabel alloc]init];
    if([self.para[self.keys[0]] isEqual:@(2)] && section==2){
        feedbackTitleLab.text = @"问题描述".rh_localized;
    }else{
        feedbackTitleLab.text = self.titles[section];
    }
    feedbackTitleLab.font = [UIFont boldSystemFontOfSize:16];
    feedbackTitleLab.textColor = kCOLOR_HEX(@"3F4443");
    [bgView addSubview:feedbackTitleLab];
    [feedbackTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.mas_offset(12);
    }];
    return header;
 
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UITableViewHeaderFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer_1"];
    if(footer == nil){
        footer = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"footer_1"];
        footer.frame = CGRectMake(0, 0, kUI_WINDOW_W, 10);
        UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 10)];
        footView.backgroundColor = CFTabViewBgColor;
        UIView *bgView = [[UIView alloc]init];
        [footView addSubview:bgView];
        bgView.backgroundColor = [UIColor whiteColor];
        bgView.frame = CGRectMake(15, 0, kUI_WINDOW_W-30, 10);
        [bgView setBottomBorder];
        [footer addSubview:footView];
    }
   
    return footer;
   
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    kWeakSelf;
    if(indexPath.section == 0){
        RHFeedBackTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PEFeedBackCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.para = self.para;
        cell.key = self.keys[indexPath.row];
        cell.selectBlock = ^{
            [weakSelf.tableView reloadData];
        };
        return cell;
    }else if(indexPath.section == 1){
        RHFbQuestionTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHFbQuestionTypeCell"];
        cell.para = self.para;
        cell.key = self.keys[indexPath.section];
        
        return cell;
    }else if (indexPath.section == 2) {
        RHFbSelectDevCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHFbSelectDevCell"];
        cell.para = self.para;
        cell.keys = self.keys[indexPath.section];
        return cell;
    }else if (indexPath.section == 3) {
        RHFbContactCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHFbContactCell"];
        cell.para = self.para;
        cell.keys = self.keys[indexPath.section];
        return cell;
    }
    
    return [UITableViewCell new];
}

@end
